# -*- coding: utf-8 -*-
import time,socket

from multiprocessing import Process
from program_top.utilities.initialisation import load_class_shared_config
from program_top.utilities.environment_and_platform import environment_initialisation
from program_top.utilities.file_and_iostream import get_current_size

class base(Process):
	def run(self):
		environment_initialisation(self)
		load_class_shared_config(self)
	
	pass


class poll_file_send_ssh(base):
	
	@staticmethod#静态函数，其实不是类成员
	def connect_to_local_ssh(ssh_port):
		s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.setblocking(0)#禁止阻塞
		s.settimeout(0.01)#超时时间
		s.connect(("localhost", ssh_port))
		return s
	
	def flush_queue_to_write_file(self,write_fd,queue):
		'''查看文件流的size是否为空，不为空则阻塞，为空才写入'''
		
		while get_current_size(write_fd):#只要文件不为空，轮询锁住
			time.sleep(self.config['sleep_timeout'])
			pass
		#文件在此为空，可以写入
		
		while queue:#从队列前面逐个入栈写入文件
			write_fd.write(queue.pop(0))
			pass
		
		write_fd.flush()
		
	def run(self):
		super(poll_file_send_ssh, self).run()
		current_connection=None
		
		read_filename=self.config['local_buffer_path']+"write_from_in.txt"
		write_filename=self.config['local_buffer_path']+"write_from_out.txt"
		sshd_port=self.config['local_ssh_port']
		
		write_file_queue=[]#写入文件队列
		
		with open(read_filename,mode="wb+") as read_file,open(write_filename,mode='wb+') as write_file:
			
			while 1:
				
				read_file.seek(0, 0)#文件指针回到开头
				data_from_file=read_file.read()
				
				try:
					data_to_file=current_connection.recv(self.config['buffer_byte'])
					
					if data_to_file:
						write_file_queue.append(data_to_file)
						self.flush_queue_to_write_file(write_file,write_file_queue)
						
					current_connection.send(data_from_file)
					
				except:#连接没创建，看是否需要重新创建
					if data_from_file==b'start':
						current_connection=self.connect_to_local_ssh(sshd_port)
						write_file.write(b'started')
						write_file.flush()
						
					time.sleep(self.config['sleep_timeout'])
					continue
			pass
		pass